package com.cvte.sunkit.tools

import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.regex.Pattern

/**
 *  @PackageName com.cvte.sunkit.tools
 *  @Description
 *  @Author lixu
 *  @Data 2023/8/29 16:07
 *  @Version 1.0
 */
object FpsToolPlus {
    private const val TAG = "FpsToolPlus"

    /**
     * 标准帧数
     */
    private const val FRAME_PER_SECOND = 60

    /**
     * 帧标准间隔
     */
    private const val FPS_PERIOD: Double = 16666.0

    /**
     * 上一次的数值
     */
    private var mLastFps = 0L
    private var mLastTime = 0L

    /**
     * 当前的值
     */
    private var mCurrentFps = 0L
    private var mCurrentTime = 0L

    /**
     * 加载  dumpsys gfxinfo
     */
    @JvmStatic
    private fun getFpsTotalData(): String {
        val cmd =
            "service call SurfaceFlinger 1013 | busybox cut -d '(' -f 2 | busybox cut -d ')' -f 0"
        try {
            val process = Runtime.getRuntime().exec(cmd)
            val reader = BufferedReader(InputStreamReader(process.inputStream), 1000)
            val line = reader.readLine().trim()
            val pattern = Pattern.compile("Parcel\\((\\w+)")
            val matcher = pattern.matcher(line)
            var result = ""
            if (matcher.find()) {
                result = matcher.group(1)
            }
            Log.i(TAG, "getFpsTotalData: $result")
            reader.close()
            return result
        } catch (ex: Exception) {
            ex.printStackTrace()
            Log.e(TAG, "load [service call SurfaceFlinger 1013] exception : $ex")
        }
        return ""
    }

    fun getFps(): Int {
        if (mLastFps == 0L) {
            mLastFps = getFpsTotalData().toLong(16)
            mLastTime = System.currentTimeMillis()
            return 60
        }
        mCurrentFps = getFpsTotalData().toLong(16)
        mCurrentTime = System.currentTimeMillis()
        val gapFps = mCurrentFps - mLastFps
        val gapTime = mCurrentTime - mLastTime
        mLastFps = mCurrentFps
        mLastTime = mCurrentTime
        if (gapFps < 0 || gapTime < 0) {
            return 0
        }
        return gapFps.toInt() * 1000 / gapTime.toInt()
    }

}